<template>
  <div>
    <el-upload
      action=""
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleFileChange"
      accept=".xlsx, .xls"
    >
      <el-button type="primary">选择Excel文件</el-button>
    </el-upload>

    <el-table :data="tableData" v-if="tableData.length > 0">
          <el-table-column type="index" label="序号" width="80" />
       <el-table-column prop="name" label="姓名" />
    <el-table-column prop="__EMPTY_1" label="性别" />
    <el-table-column prop="__EMPTY_3" label="身份证" />
    <el-table-column prop="__EMPTY_3" label="社区">
       蟠桃社区
    </el-table-column>
    <el-table-column prop="__EMPTY_3" label="住址">
       
    </el-table-column>

    
    </el-table>
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx";
import { data1 } from "@/utils/data1.js";
import { data2 } from "@/utils/data2.js";
import { data3 } from "@/utils/data3.js";
let arr = []
data3().forEach(item=>{
  arr.push({ name: item.__EMPTY, gender: item.__EMPTY_1, id: item.__EMPTY_2, address: item.__EMPTY_3 })
})
console.log(JSON.stringify(arr))
const tableData = ref([]);
const tableHeaders = ref([]);
// tableData.value.push(...data1());
// tableData.value.push(...data2());
tableData.value.push(...data3());

const handleFileChange = async (file) => {
  // 检查文件类型
  if (!file.raw) return;
  if (
    ![
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      "application/vnd.ms-excel",
    ].includes(file.raw.type)
  ) {
    ElMessage.error("请上传Excel文件");
    return;
  }

  try {
    // 读取文件数据
    const data = await readExcel(file.raw);
    console.log(data);
    tableData.value = data;
    if (data.length > 0) {
      tableHeaders.value = Object.keys(data[0]);
    }
    ElMessage.success("文件读取成功");
  } catch (error) {
    console.error("读取Excel失败:", error);
    ElMessage.error("文件读取失败");
  }
};

const readExcel = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = (e) => {
      try {
        const data = e.target.result;
        const workbook = XLSX.read(data, { type: "array" });

        // 获取第一个工作表
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];

        // 转换为JSON
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        resolve(jsonData);
      } catch (error) {
        reject(error);
      }
    };

    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file);
  });
};
</script>